<?php
/**
* d:\wamp2.5\bin\php\php5.5.12\php.exe D:\wamp2.5\www\_oschina\tank\start_ws.php
* D:\wamp\bin\php\php5.5.12\php.exe D:\www\osc\tank\start_ws.php
* php /www/wwwroot/tank/start_ws.php
 * ******
* d:\wamp2.5\bin\php\php5.5.12\php.exe D:\wamp2.5\www\_oschina\tank\start_work.php
* D:\wamp\bin\php\php5.5.12\php.exe D:\www\osc\tank\start_work.php
 *  ulimit -HSn 102400
 *  php -c /www/server/php/54/etc/php.cli.ini /www/wwwroot/tank/start_work.php start -d (配置文件允许执行exec方法)
*/
$cfg_timezone = 8;
$time51 = $cfg_timezone * -1;
@date_default_timezone_set('Etc/GMT'.$time51);

$sys = (PATH_SEPARATOR == ':') ? 'Unix' : 'Win';
$m = [];
if ($sys == 'Unix') {
    $cmd = 'ps -aux | grep "tank/start_ws.php"';
    $ps = [];
    exec($cmd, $ps);
    foreach($ps as $i => $p){
        if(strstr($p, 'grep')){
            unset($ps[$i]);
        }
    }
    if(count($ps) > 1){
        die('has exec:'.$ps[0]);
    }
}

require('class_ws.php');
$ws = new Ws('192.168.2.101', '8080', 10);
$ws = new Ws('192.168.118.220', '8080', 10);
$ws = new Ws('122.114.76.193', '12345', 10);
$ws->function['add'] = 'user_add_callback';
$ws->function['send'] = 'send_callback';
$ws->function['close'] = 'close_callback';
$ws->start_server();
 
//回调函数们
function user_add_callback($index, $ws) {
        $data = array();
        $data[0] = 'user_add';
        $data['wsid'] = $index;
        $data['wc'] = count($ws->accept);
        $data = json_encode(array($data));
 	send_to_all($data, $ws);
}
 
function close_callback($index, $ws) {
        $data = array();
        $data[0] = 'user_close';
        $data['wsid'] = $index;
        $data['wc'] = count($ws->accept);
        $data = json_encode(array($data));
	send_to_all($data, $ws);
}
 
function send_callback($data, $index, $ws) {
    $data1 = json_decode($data, true);
    if(!is_array($data1)){
        var_dump($data);
        return;
    }
    $data = json_decode($data, true);
    foreach($data as $i => $v){
        $data[$i]['wsid'] = $index;
        $data[$i]['wc'] = count($ws->accept);
    }
    $data = json_encode($data);
	send_to_all($data, $ws);
}
 
function send_to_all($data, $ws){
	$res = $ws->frame($data);
	foreach ($ws->accept as $key => $value) {
		socket_write($value, $res, strlen($res));
	}
}
